package code.whmmm.util.date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 使用了 ThreadLocal 的日期格式化类
 * <br/><br/>
 * 创建时间: 2020/5/8 15:22
 *
 * @author whmmm
 */
public class TimeFormat {

    private static final Logger log = LoggerFactory.getLogger(TimeFormat.class);

    private final ThreadLocal<SimpleDateFormat> cache = new ThreadLocal<SimpleDateFormat>();

    private final String pattern;

    public TimeFormat(String pattern) {
        this.pattern = pattern;
        cache.set(new SimpleDateFormat(pattern));
    }

    public String format(Date date) {
        return getCache().format(date);
    }


    public Date parse(String timeString) {
        try {
            return getCache().parse(timeString);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


    private SimpleDateFormat getCache() {
        SimpleDateFormat format = cache.get();
        if (format == null) {
            format = new SimpleDateFormat(pattern);
            cache.set(new SimpleDateFormat(pattern));
        }
        return format;
    }

}
